import { NextResponse } from 'next/server';
import path from 'path';
import * as fs from 'fs';
import { parse } from 'csv-parse/sync';
import { SpecialtyTableData } from '@/lib/types';

const DATA_DIR = path.join(process.cwd(), 'excel', '06-21');
const SPECIALTY_FILES = [
  '设备表-配管专业.csv',
  '设备表-电气专业.csv',
  '设备表-暖通专业.csv',
  '设备表-通信专业.csv',
  '设备表-仪表专业.csv',
];

export function GET() {
  try {
    const allSpecialtyData: SpecialtyTableData[] = [];

    SPECIALTY_FILES.forEach((filename) => {
      console.log(`[Equipment-Table-API] Processing file: ${filename}`);
      const filePath = path.join(DATA_DIR, filename);
      if (!fs.existsSync(filePath)) {
        console.warn(`[Equipment-Table-API] File not found, skipping: ${filename}`);
        return;
      }

      const content = fs.readFileSync(filePath, 'utf-8');
      const cleanedContent = content.charCodeAt(0) === 0xFEFF ? content.substring(1) : content;
      
      const records: (string | number | null)[][] = parse(cleanedContent, {
        columns: false,
        skip_empty_lines: true,
      });

      if (records.length === 0) return;

      const headers = records.shift() as string[]; 
      const specialtyName = filename.replace('设备表-', '').replace('.csv', '');

      if (headers && records.length > 0) {
        allSpecialtyData.push({
          specialty: specialtyName,
          headers,
          rows: records,
        });
      }
    });

    return NextResponse.json(allSpecialtyData);
  } catch (error) {
    console.error(`[Equipment-Table-API] Fatal error while processing equipment CSV files: ${error}`);
    const message = error instanceof Error ? error.message : 'An unknown error occurred while reading equipment data.';
    return NextResponse.json({ error: message }, { status: 500 });
  }
} 